package com.canbot.u05.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.canbot.u05.bean.AudioInfo;

import java.util.ArrayList;
import java.util.List;

public class AudioController {

        private ContentResolver cResolver;

        public AudioController(Context context) {
                cResolver = context.getContentResolver();
        }

        /**
         * 扫描媒体库，获得音频文件
         *
         * @return
         */
        public List<AudioInfo> getMedia() {
                List<AudioInfo> audioInfos = new ArrayList<AudioInfo>();
                String[] mediaColumns = {MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.MIME_TYPE,
                        MediaStore.Audio.Media.TITLE

                };

                Cursor cursor = cResolver.query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns, null,
                        null, null);
                if (cursor != null) {
                        if (cursor.moveToFirst()) {
                                do {
                                        AudioInfo audioInfo = new AudioInfo();
                                        int id = cursor.getInt(
                                                cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                                        String path = cursor.getString(cursor
                                                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                                        String mimeType = cursor.getString(cursor.getColumnIndexOrThrow(
                                                MediaStore.Audio.Media.MIME_TYPE));
                                        String name = cursor.getColumnName(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                                        audioInfo.setId(id);
                                        audioInfo.setPath(path);
                                        audioInfo.setMimeType(mimeType);
                                        audioInfo.setName(name);
                                        audioInfos.add(audioInfo);
                                }
                                while (cursor.moveToNext());
                        }

                }
                cursor.close();
                return audioInfos;
        }
}
